package com.maibo.lys.useddelete;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by LYS on 2017/2/28.
 */

public class RainbowBar extends View {

    int hSpace = dip2px(getContext(), 80);
    int vSpace = dip2px(getContext(), 4);
    int barColor = Color.parseColor("#0000ff");
    Paint mPaint;

    public RainbowBar(Context context) {
        super(context);
    }

    public RainbowBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RainbowBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取自定义属性中的值
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.rainbowbar, 0, 0);
        //第二个参数为默认值
        hSpace = array.getDimensionPixelSize(R.styleable.rainbowbar_rainbowbar_hspace, hSpace);
        vSpace = array.getDimensionPixelSize(R.styleable.rainbowbar_rainbowbar_vspace, vSpace);
        barColor = array.getColor(R.styleable.rainbowbar_rainbowbar_color, barColor);
        //及时回收
        array.recycle();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);//防锯齿
        mPaint.setColor(barColor);
        mPaint.setStrokeWidth(vSpace);
    }

    int index = 0;
    int space = dip2px(getContext(), 10);
    float startX = 0;
    float delta = 10f;
    int tag = 0;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //get screen width
        float sw = this.getMeasuredWidth();
        if (startX >= sw + (hSpace + space)- (sw % (hSpace + space)) ) {//
            startX = 0;
        } else {
            startX += delta;
        }
        float start = startX;
        // draw latter parse
        while (start < sw) {
            Log.e("start1:", start + "");
            canvas.drawLine(start, 0, start + hSpace, 0, mPaint);
            start += (hSpace + space);

        }

        start = startX - space - hSpace;

        // draw front parse
        while (start >= -hSpace) {
            Log.e("start2:", start + "");
            canvas.drawLine(start, 0, start + hSpace, 0, mPaint);
            start -= (hSpace + space);
        }
        if (index >= 700000) {
            index = 0;
        }
        //通过一次次重绘来显示滚动效果
        invalidate();

    }


    /**
     * 把密度转换为像素
     */
    public static int dip2px(Context context, float px) {
        final float scale = getScreenDensity(context);
        return (int) (px * scale + 0.5);
    }

    /**
     * 得到设备的密度
     */
    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }
}
